package com.thread;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import com.Constant;
import com.android.scj.tc.Connection;
import com.android.scj.tc.TerminalService;
import com.android.scj.tc.TcAppFolw;
import com.baseutils.SpfUtils;
import com.equipment.SetParameterResponse;
import com.util.HexUtil;

import java.io.IOException;
import java.util.NoSuchElementException;

/**
 * 脱机线程类
 *
 * @author 刘亚东
 *
 */
@SuppressWarnings("unused")
public class OffLineThread extends Thread {
	// 与设备通信服务类
	private TerminalService service = TerminalService.getService();
	// 通信类
	private static Connection con = Connection.getConnection();
	// 表示是否初始化
	public static boolean isFind = false;
	/**
	 *  是否脱机状态 false为联机 true为脱机
	 */
	public static boolean isOff = false;

	public static String version = "";
	public static String hardVersion = "";
	public static	Context context;

	public static Bundle bundle = null;
	// PSAM卡是否存在
	public boolean isPSAM1 = false;
	public boolean isPSAM2 = false;
	private String type = "";
	// 脱机初始化两张PSAM卡
	private String psam = "";
	private String psam2 = "";
	private static TcAppFolw equiCon;


	public String getPsam2() {
		return psam2;

	}

	public void setPsam2(String psam2) {
		this.psam2 = psam2;
	}

	public String getPsam() {
		return psam;
	}

	public void setPsam(String psam) {
		this.psam = psam;
	}

	public OffLineThread(String type,Context context ) {
		this.type = type;
		this.context = context;
		boolean	psamopen = (boolean) SpfUtils.get(context, Constant.Check_Psam, true);
		equiCon =  new TcAppFolw(context,psamopen);
	}

	public boolean isPSAM1() {
		return isPSAM1;
	}

	public void setPSAM1(boolean isPSAM1) {
		this.isPSAM1 = isPSAM1;
	}

	public boolean isPSAM2() {
		return isPSAM2;
	}

	public void setPSAM2(boolean isPSAM2) {
		this.isPSAM2 = isPSAM2;
	}

	public void print(String key, String value) {
		Log.e(key, value + "");
	}

	/**
	 * 发送A9
	 * 设置参数
	 * @throws NoSuchElementException
	 * @throws Exception
	 */
	public void sendA9() throws NoSuchElementException, IOException, Exception {
		String str = con.send(service.sendA9(),context);
		print("发出A9", service.sendA9());
		print("A9收到的数据", str);
		SetParameterResponse sr = service.adoptA9(str);
	}

	public void sendA9_2() throws NoSuchElementException, IOException, Exception {
		String str = con.send(service.sendA9_2(),context);
		print("发出A9_2", service.sendA9_2());
		print("A9收到的数据", str);
		SetParameterResponse sr = service.adoptA9(str);
	}
	/**
	 * 获取设备版本
	 *
	 * @throws NoSuchElementException
	 * @throws IOException
	 * @throws Exception
	 */
	public void searchVer() throws NoSuchElementException, IOException,
			Exception {
		String baowen = service.sendA0();
		print("发送A0：", baowen);
		String context2 = con.send(baowen,context);
		print("接收B0：", context2);
		String result = service.adoptB0(context2);
		version = result.substring(0, 4);
		hardVersion = result.substring(result.lastIndexOf("_")+1);
	}

	public void appLog(String date) {

	}

	/**
	 * 发送AA
	 *
	 * @throws NoSuchElementException
	 * @throws IOException
	 *             ,Exception
	 * @throws Exception
	 */
	public void offLine() throws NoSuchElementException, IOException, Exception {



		//ChineseDetectionOBURequest gbDetectionObuRq  =  new ChineseDetectionOBURequest();
		//String baowen = gbDetectionObuRq.command("39");
		String baowen =  service.sendC5();
		appLog("T," + baowen);
		print("发送出的C5", baowen);

		String context2 = con.send(baowen,context);
		print("C5收到的数据", context2);
		appLog("R," + context2);

		service.adoptD5(context2);


	}

//	public void offLineDetection(int nType) throws Exception{
//		if(nType==0)
//			equiCon.ObuOfflineExmin();
//		else
//			equiCon.ObuOfflineExminNoPsam();
//
//	}
	public void readCard() {
		String baowen = "";
		String recv = "";
		//1、非接触卡复位
		try {
			equiCon.PsamReset("FF");
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoSuchElementException(e.getMessage());
		}

		//2、非接触卡选1001
		try {
			equiCon.PsamCmd("FF", "010700A40000021001");
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoSuchElementException("非接触卡选1001,"+e.getMessage());
		}

		//3、非接触卡读15
		try {
			recv = equiCon.PsamCmd("FF", "010500B095002B");
			String ccRead15 = recv;
			if (ccRead15 == null) {
				throw new NumberFormatException("读15文件失败");
			}
			print("test", "file15="+ccRead15);
			String Issue = ccRead15.substring(0, 8*2);
			String ECardType = ccRead15.substring(8*2, 9*2);
			String ECardVer = ccRead15.substring(9*2, 10*2);
			String ECardNetNo = ccRead15.substring(10*2, 12*2);
			String ECardId = ccRead15.substring(12*2, 20*2);
			String StartTime = ccRead15.substring(20*2, 24*2);
			String EndTime = ccRead15.substring(24*2, 28*2);
			String EVehicleNo = ccRead15.substring(28*2, 40*2);
			String EUserType = ccRead15.substring(40*2, 41*2);
			String EVehicleColor = ccRead15.substring(41*2, 43*2);
			print("test", "Issue="+Issue+"\nECardId="+ECardId);
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoSuchElementException("非接触卡读15,"+e.getMessage());
		}

		//4、读余额
		try {
			recv = equiCon.PsamCmd("FF", "0105805C000204");
			String amount = recv.substring(0, 4*2);
			Log.e("test", "amount="+amount);
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoSuchElementException("非接触卡读余额,"+e.getMessage());
		}
	}

	private void LoadBundMess(int nType)throws Exception
	{
		bundle = new Bundle();
		bundle.putString("OBUMAC", equiCon.GetOBUMAC());
		bundle.putString("OBUSERIALNUMBER",equiCon.GetOBUSerialNumber());
		bundle.putString("OBUSTATUS", equiCon.GetObuStatus());
		bundle.putString("OBUISSUER", HexUtil.HexToAsciiString(equiCon.GetOBUArea()));
		bundle.putString("OBUCONTRACTTYPE", equiCon.GetObuContractType());
		bundle.putString("OBUCONTRACT", equiCon.GetObuContract());
		bundle.putString("OBUBATTERY", equiCon.GetObuBattery());
		bundle.putString("OBUDATE", TcAppFolw.convertDate(equiCon.GetObuDate().substring(0, 8)));
		bundle.putString("OBUDATE2", TcAppFolw.convertDate(equiCon.GetObuDate().substring(8, 16)));


		bundle.putString("VLP",equiCon.VLP);
		if(nType==0)
		{
//			=====================新代码开始============
			bundle.putString("VLP",equiCon.VLP);
			bundle.putString("VLPC",equiCon.VLPC);
//			bundle.putString("VLPC_1", equiCon.VLPC_1);
			bundle.putString("VCLASS",equiCon.VClass);
			bundle.putString("VUSERTYPE", equiCon.VUserType);
			bundle.putString("VSIZE", equiCon.VSize);
			bundle.putString("VSIZE2", equiCon.VSize2);
			//value
//			bundle.putString("Allowableload_VWheel", equiCon.Allowableload_VWheel);
//			bundle.putString("curbweight_VAxis", equiCon.curbweight_VAxis);
//			bundle.putString("totalmass_VAxisWidth", equiCon.totalmass_VAxisWidth);
//			bundle.putString("numberofpeople_VWeight", equiCon.numberofpeople_VWeight);
//			bundle.putString("VDESCIBE", equiCon.VDescribe);
//			bundle.putString("Vehicle_VEngineSN", equiCon.Vehicle_VEngineSN);




			//	=====================新代码结束============


//			bundle.putString("VLPC",equiCon.VLPC);
//			bundle.putString("VCLASS",equiCon.VClass);
//			bundle.putString("VUSERTYPE", equiCon.VUserType);
//			bundle.putString("VSIZE", equiCon.VSize);
//			bundle.putString("VSIZE2", equiCon.VSize2);
//			bundle.putString("VWHEEL", equiCon.VWheel);
//			bundle.putString("VAXIS", equiCon.VAxis);
//			bundle.putString("VAXISWIDTH", equiCon.VAxisWidth);
//			bundle.putString("VWeight", equiCon.VWeight);
//			bundle.putString("VDESCIBE", equiCon.VDescribe);
//			bundle.putString("VENGINESN", equiCon.VEngineSN);
		}
		bundle.putString("CARDISSUER", equiCon.GetCardIssuer());
		bundle.putString("CARDTYPE", equiCon.GetCardType());
		bundle.putString("CARDVERSION", equiCon.GetCardVersion());
		bundle.putString("CARDNETNUMBER", equiCon.GetCardNetNumber());
		bundle.putString("CARDSERIALNUMBER", equiCon.GetCardSerialNumber());
		bundle.putString("CARDVLP",equiCon.GetCardVlp());
		bundle.putString("CARDVLPC",equiCon.GetCardVehicleColor());
		bundle.putString("CARDUSERTYPE",equiCon.GetCardUserType());
		bundle.putString("CARDBALANCE", equiCon.GetCardBalance());
		bundle.putString("CARDDATE", equiCon.GetCardDate1());
		bundle.putString("CARDDATE2",equiCon.GetCardDate2());

	}

	/**
	 * 检查PSAM卡是否存在
	 *
	 * @throws Exception
	 * @throws InterruptedException
	 * @throws IOException
	 */
	public void checkCard() throws IOException, InterruptedException, Exception {
		String baowen = service.sendAE("3", "1");
		appLog("T," + baowen);
		print("发送出的AE", baowen);
		String context2 = con.send(baowen,context);
		print("收到的BE：", context2);
		appLog("R," + context2);

		baowen = service.sendA1(psam);
		try {
			print("检查PSAM1卡是否存在：", baowen);
			context2 = con.send(baowen,context);
			print("检查PSAM1卡结果：", context2);
			// 解析失败表示PSAM不存在
			service.adoptA1(context2);
			isPSAM1 = true;
		} catch (Exception e) {
			isPSAM1 = false;
		}
		baowen = service.sendA1(psam2);
		try {
			print("检查PSAM2卡是否存在：", baowen);
			context2 = con.send(baowen,context);
			print("检查PSAM2卡结果：", context2);
			// 解析失败表示PSAM不存在
			service.adoptA1(context2);
			isPSAM2 = true;
		} catch (IOException e) {
			isPSAM2 = false;
//			SendLoop.getExceptionMessage("检查PSAM卡失败：" + e.getMessage());
		} catch (Exception e) {
			isPSAM2 = false;
		}
//		CodeActivity.isWord = true;
	}

	@Override
	public void run() {

		if (type.equals("A9")) {//参数设置
			try {
				sendA9();
				isFind = true;
			} catch (Exception e) {
//				SendLoop.getExceptionMessage("初始化失败：" + e.getMessage());
			}
		}else if (type.equals("A9_2")) {//参数设置
			try {
				sendA9_2();
				isFind = true;
			} catch (Exception e) {
//				SendLoop.getExceptionMessage("初始化失败：" + e.getMessage());
			}
		}

	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

}
